package com.shenmazong.servertalkmarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.pojo.*;
import com.shenmazong.servertalkmarket.mapper.*;
import com.shenmazong.servertalkmarket.service.MarketService;
import com.shenmazong.utils.ConstUtils;
import com.shenmazong.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MarketServiceImpl implements MarketService {

    @Autowired
    TbMarketMessageMapper tbMarketMessageMapper;

    @Autowired
    TbAdminMapper tbAdminMapper;

    @Autowired
    TbMarketCouponMapper tbMarketCouponMapper;

    @Autowired
    TbStudentMapper tbStudentMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TbStudentCouponMapper tbStudentCouponMapper;

    /**
     * TODO addMarketMessage 增加活动消息
     * @param userId
     * @param message
     * @return
     */
    @Override
    public ResponseResult addMarketMessage(Integer userId, String message) {
        ResponseResult result = ResponseResult.SUCCESS();
        //HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断管理是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null || !admin.getAdminStatus().equals(0)) {
            result.setFailMessage("管理员不存");
            return result;
        }

        //--2 增加消息
        TbMarketMessage msg = new TbMarketMessage();
        msg.setUserId(userId);
        msg.setMessage(message);

        tbMarketMessageMapper.insert(msg);
        if(msg.getId() != null) {
            return result;
        }

        result.setFailMessage("增加活动消息失败");
        return result;
    }

    /**
     * TODO delMarketMessage 删除活动消息
     * @param userId
     * @param msgId
     * @return
     */
    @Override
    public ResponseResult delMarketMessage(Integer userId, Integer msgId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 判断管理是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null || !admin.getAdminStatus().equals(0)) {
            result.setFailMessage("管理员不存");
            return result;
        }

        //--2 删除消息
        tbMarketMessageMapper.deleteById(msgId);
        return result;
    }

    /**
     * TODO publishMarketMessage 正式发布活动消息
     * @param userId
     * @param msgId
     * @return
     */
    @Override
    public ResponseResult publishMarketMessage(Integer userId, Integer msgId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 判断管理是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null || !admin.getAdminStatus().equals(0)) {
            result.setFailMessage("管理员不存");
            return result;
        }

        //--2 发布消息
        TbMarketMessage message = tbMarketMessageMapper.selectById(msgId);
        if(message == null) {
            result.setFailMessage("活动消息不存在");
            return result;
        }

        message.setStatus(1);
        tbMarketMessageMapper.updateById(message);

        return result;
    }

    /**
     * TODO getMarketMessage 获取最后发布的活动信息
     * @return
     */
    @Override
    public ResponseResult getMarketMessage() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        TbMarketMessage message = tbMarketMessageMapper.selectOne(
                new QueryWrapper<TbMarketMessage>()
                        .eq("status", 1)
                        .orderByDesc("create_time")
                        .last("limit 1")
        );
        if(message == null) {
            result.setFailMessage("没有可以展示的活动消息");
            return result;
        }

        resultMap.put("message", message);
        result.setResult(resultMap);
        return result;
    }

    /**
     * TODO addMarketCoupon 添加营销活动
     * @param userId
     * @param teacherId
     * @param price
     * @param classCount
     * @return
     */
    @Override
    public ResponseResult addMarketCoupon(Integer userId, Integer teacherId, Long price, Integer classCount) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 判断管理是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null || !admin.getAdminStatus().equals(0)) {
            result.setFailMessage("管理员不存");
            return result;
        }

        //--2 检查是否存在没有举行活动
        TbMarketCoupon coupon = tbMarketCouponMapper.selectOne(
                new QueryWrapper<TbMarketCoupon>().eq("status", 0).last("limit 1")
        );
        if(coupon != null) {
            result.setFailMessage("有活动还没有完成");
            return result;
        }

        //--3 创建新的营销活动
        coupon = new TbMarketCoupon();
        coupon.setUserId(userId);
        coupon.setTeacherId(teacherId);
        coupon.setPrice(price);
        coupon.setClassCount(classCount);

        tbMarketCouponMapper.insert(coupon);
        if(coupon.getId() != null) {
            return result;
        }

        result.setFailMessage("添加活动失败");

        return result;
    }

    /**
     * TODO grabMarketClass 抢购优惠课程的券
     * @param userId
     * @return
     */
    @Override
    public ResponseResult grabMarketClass(Integer userId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 判断学生在不在
        TbStudent student = tbStudentMapper.selectById(userId);
        if(student == null) {
            result.setFailMessage("学生不存在");
            return result;
        }

        //-- 2 判断有没有课程可以抢
        // waiting-coupon
        if(!redisTemplate.hasKey(ConstUtils.WAITING_COUPON_KEY)) {
            result.setFailMessage("请您稍后再试");
            return result;
        }
        else {
            Long size = redisTemplate.opsForList().size(ConstUtils.WAITING_COUPON_KEY);
            if(size <= 0) {
                result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
                return result;
            }
        }

        //--3 是否已经抢过了
        if(redisTemplate.opsForSet().isMember(ConstUtils.CATCH_COUPON_KEY, userId)) {
            result.setFailMessage("亲，您已经抢过了。欢迎下次再来！");
            return result;
        }

        //--4 终于开始抢了
        Integer couponId = (Integer) redisTemplate.opsForList().rightPop(ConstUtils.WAITING_COUPON_KEY);
        if(couponId == null) {
            result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
            return result;
        }

        redisTemplate.opsForSet().add(ConstUtils.CATCH_COUPON_KEY, userId);

        // 给rabbitmq发送消息 -》 接收消息 -》 写入到数据库
        TbStudentCoupon tbStudentCoupon = new TbStudentCoupon();
        tbStudentCoupon.setStudentId(userId);
        tbStudentCoupon.setCouponId(couponId);

        // -- 计算券的过期时间
//        Date nowDate = new Date();
//        Long nowTime = nowDate.getTime();
//        nowTime += 1000*60*60*24*7;
//
//        nowDate.setTime(nowTime);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String strNowDate = simpleDateFormat.format(nowDate);
//        tbStudentCoupon.setEndTime(strNowDate);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 7);
        String strNowDate = simpleDateFormat.format(c.getTime());
        tbStudentCoupon.setEndTime(strNowDate);

        tbStudentCouponMapper.insert(tbStudentCoupon);
        if(tbStudentCoupon.getId() != null) {
            return result;
        }

        //--5 提示抢购完成（提示成功，失败）
        result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
        return result;
    }

    /**
     * TODO getMarketClassByPage 查看自己拥有的优惠券
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getMarketClassByPage(Integer userId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断学生在不在
        TbStudent student = tbStudentMapper.selectById(userId);
        if(student == null) {
            result.setFailMessage("学生不存在");
            return result;
        }

        //--2 获取所有券的列表
        List<TbStudentCoupon> coupons = tbStudentCouponMapper.getMarketClassByPage(userId);
        if(coupons == null || coupons.size() <= 0) {
            result.setFailMessage("没有优惠券");
            return result;
        }

        resultMap.put("coupons", coupons);
        result.setResult(resultMap);

        return result;
    }

    @Override
    public ResponseResult doBeginGrab(Integer userId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 检查优惠信息
        TbMarketCoupon marketCoupon = tbMarketCouponMapper.selectOne(
                new QueryWrapper<TbMarketCoupon>()
                        .lambda()
                        .eq(TbMarketCoupon::getStatus, 0)
                        .orderByDesc(TbMarketCoupon::getCreateTime)
                        .last("limit 1")
        );
        if(marketCoupon == null) {
            log.info("没有特惠活动");
            return result;
        }

        //--2 生产优惠券，放入redis
        // 循环加入优惠券
        for (int idx = 0; idx < marketCoupon.getClassCount(); idx++) {
            int id = marketCoupon.getId();
            redisTemplate.opsForList().leftPush(ConstUtils.WAITING_COUPON_KEY, id);
        }
        // 设置优惠券的过期时间
        redisTemplate.expire(ConstUtils.WAITING_COUPON_KEY, 1, TimeUnit.HOURS);

        // 设置以抢到优惠券用户集合的时间
        redisTemplate.expire(ConstUtils.CATCH_COUPON_KEY, 1, TimeUnit.HOURS);

        //--3 修改优惠活动的状态
        marketCoupon.setStatus(1);
        tbMarketCouponMapper.updateById(marketCoupon);

        //
        System.out.println("开始抢购了");
        return result;
    }
}
